import gql from 'graphql-tag'

export function createInsert(model) {
  const { table, formInputs = {} } = model || {}
  const keys = []

  for (let key in formInputs) {
    const input = formInputs[key] || {}

    if (!key || input['type'] === 'password') {
      continue
    }
    if (Array.isArray(input['_keys'])) {
      keys.push(`${key} {
        ${input['_keys'].join('\n')}
      }`)
    } else {
      keys.push(key)
    }
  }

  return gql`
    mutation ($object: ${table}_insert_input!) {
      insert_${table}_one (object: $object) {
        ${keys.join('\n')}
      }
    }
  `
}

export function createUpdate(model, idKey = 'id', idType) {
  const { table } = model || {}

  return gql`
    mutation ($${idKey}: ${idType || (idKey === 'id' ? 'Int' : 'uuid')}!, $object: ${table}_set_input!) {
      update_${table} (
        where: { ${idKey}: { _eq: $${idKey} } }
        _set: $object
      ) {
        affected_rows
      }
    }
  `
}

export function createDelete(
  model,
  idKey = 'id',
  useSoftDelete = true,
  idType
) {
  const { table } = model || {}

  return gql`
    mutation ($ids: [${idType || (idKey === 'id' ? 'Int' : 'uuid')}!]!) {
      ${useSoftDelete ? 'update' : 'delete'}_${table} (
        where: { ${idKey}: { _in: $ids } }
        ${useSoftDelete ? '_set: { deleted_at: "now()" }' : ''}
      ) {
        affected_rows
      }
    }
  `
}

export function createRevert(
  model,
  idKey = 'id',
  idType
) {
  const { table } = model || {}

  return gql`
    mutation ($ids: [${idType || (idKey === 'id' ? 'Int' : 'uuid')}!]!) {
      update_${table} (
        where: { ${idKey}: { _in: $ids } }
        _set: { deleted_at: null }
      ) {
        affected_rows
      }
    }
  `
}

export function createMutation(
  model,
  idKey = 'id',
  useSoftDelete = true
) {
  return {
    insert: createInsert(model),
    update: createUpdate(model, idKey),
    remove: createDelete(model, idKey, useSoftDelete),
    revert: createRevert(model, idKey)
  }
}
